/**
 * ---------------------------
 * Time: 2017/8/6 18:28.
 * Author: Cangshi
 * View: http://palerock.cn
 * ---------------------------
 */
define(['app', 'zepto'], function (app, $) {
    app.controller('default', function ($http, $scope, $route, $routeParams, configService, deviceService, logger, configDao, ObjectUtils, MaintainTemplate, MaintainPlan, ColorUtils, ArrayUtils, templateService, Device) {
            $scope.myWord = '欢迎使用设备管理器';
            $scope.devices = [];
            // 批量选择的默认选项
            $scope.chooseDevices = [];
            // 排序模型
            $scope.orderModel = {
                index: 2,
                // 升降序，1升序，0降序
                order: 0,
                // 排序模板
                orderOption: [{
                    name: '按编号排序',
                    value: 0,
                    orderBy: {
                        sortBy: 'deviceNo'
                    }
                }, {
                    name: '按设备名排序',
                    value: 1,
                    orderBy: {
                        sortBy: 'deviceName'
                    }
                }, {
                    name: '按所有保养的最大百分比排序',
                    value: 2,
                    orderBy: {
                        sortBy: 'maxPercentage'
                    }
                }, {
                    name: '按一级保养的百分比排序',
                    value: 3,
                    orderBy: {
                        sortBy: 'maintainPlans.0.currentMaxPercentage'
                    }
                }, {
                    name: '按二级保养的百分比排序',
                    value: 4,
                    orderBy: {
                        sortBy: 'maintainPlans.1.currentMaxPercentage'
                    }
                }, {
                    name: '按三级保养的百分比排序',
                    value: 5,
                    orderBy: {
                        sortBy: 'maintainPlans.2.currentMaxPercentage'
                    }
                }, {
                    name: '按是否设置备注排序',
                    value: 6,
                    orderBy: {
                        sortBy: 'memorandum.exist'
                    }
                }],
                change: function () {
                    var _this = this;
                    if ($scope.isBatch) {
                        $.confirm('改变排序方式会清空所有批量选项，继续？', function () {
                            app.filterOptionsAction('选择排序方式', _this.orderOption, _this.index, function (index) {
                                _this.index = index;
                                $scope.$digest();
                            });
                        });
                        return;
                    }
                    app.filterOptionsAction('选择排序方式', this.orderOption, this.index, function (index) {
                        _this.index = index;
                        $scope.$digest();
                    })
                },
                switchOrder: function () {
                    var _this = this;
                    if ($scope.isBatch) {
                        $.confirm('改变排序方式会清空所有批量选项，继续？', function () {
                            if (_this.order == 0) {
                                _this.order = 1;
                            } else {
                                _this.order = 0;
                            }
                            $scope.$digest();
                        });
                        return;
                    }
                    if (this.order == 0) {
                        this.order = 1;
                    } else {
                        this.order = 0;
                    }
                },
                // 获取当前排序设置
                getSetting: function () {
                    var chooseOption = this.orderOption[this.index];
                    chooseOption.orderBy.order = this.order;
                    return chooseOption;
                }
            };
            // 监听排序
            $scope.$watch('orderModel.index', function () {
                $scope.orderModel.chooseOption = $scope.orderModel.getSetting();
            });
            $scope.$watch('orderModel.order', function () {
                $scope.orderModel.chooseOption = $scope.orderModel.getSetting();
            });
            $scope.$watch('orderModel.chooseOption', function () {
                $scope.devices = ObjectUtils.sortingArrayByProperty(
                    $scope.devices,
                    $scope.orderModel.chooseOption.orderBy.sortBy,
                    $scope.orderModel.chooseOption.orderBy.order
                );
                $scope.clearBatchOptions();
            }, true);
            // 默认颜色配置
            $scope.colorSetting = [{
                baseLine: 1,
                colorCode: 'f00'
            }, {
                baseLine: 0,
                colorCode: '000000'
            }];
            // 用于获取百分比的渐变色
            Number.prototype.gradientColorsPercentage = function (colorSettings) {
                var orderedSetting = ObjectUtils.sortingArrayByProperty(colorSettings, 'baseLine', 1);
                var start = '000';
                var end = null;
                var percentage = this;
                ArrayUtils.ergodicArrayObject(this, orderedSetting, function (setting, i) {
                    if (setting != null && this >= setting.baseLine && orderedSetting[i + 1] == null) {
                        start = '#' + setting.colorCode;
                        return -1;
                    }
                    if (this >= setting.baseLine && this < orderedSetting[i + 1].baseLine) {
                        start = '#' + setting.colorCode;
                        end = '#' + orderedSetting[i + 1].colorCode;
                        percentage = (this - setting.baseLine) / (orderedSetting[i + 1].baseLine - setting.baseLine);
                        return -1;
                    }
                });
                return ColorUtils.gradientColorsPercentage(start, end, percentage);
            };
            $scope.setObject = function (name, value) {
                $scope[name] = value;
            };
            // 清空批量选项
            $scope.clearBatchOptions = function () {
                $scope.isBatch = false;
                $scope.chooseDevices = [];
            };
            // 初始化配置
            $scope.initConfig = function (cb) {
                configService.getInitConfig(function (r, e) {
                    $scope.myWord = r.welcomeWords;
                    $scope.colorSetting = r.colorSetting;
                    $scope.$digest();
                    if (cb) {
                        cb.call(window);
                    }
                });
            };
            $scope.reloadDevices = function () {
                deviceService.showAllDevices(function (r, e) {
                    $scope.devices = r;
                    $scope.$digest();
                }, $scope.orderModel.getSetting().orderBy);
            };
            var init = function () {
                $scope.initConfig();
                $scope.reloadDevices();
                // 设定默认的模板
                $scope.defaultMaintainTemplate = new MaintainTemplate({
                    templateDiscription: '（来自默认模板[所有模板的参考]）',
                    templateName: '',
                    maintainPlans: [
                        new MaintainPlan({
                            maintainName: '一级保养'
                        }),
                        new MaintainPlan({
                            maintainName: '二级保养'
                        }),
                        new MaintainPlan({
                            maintainName: '三级保养'
                        })
                    ]
                });
            };
            init();
            // 初始化sui框架
            $scope.suiMobileInit = function (jsPath) {
                app.suiInit(jsPath);
            };
            $scope.initCss = function (cssPath) {
                app.initCss(cssPath);
            };
            // 更新欢迎语
            $scope.updateWelcomeWords = function () {
                app.contentPrompt('请输入想显示在这里的话', function (message) {
                    if (!message) {
                        $.alert('欢迎语不能为空');
                    }
                    configService.setWelcomeWords(message, function () {
                        $scope.myWord = message;
                        $scope.$digest();
                    });
                }, $scope.myWord);
            };

            // 跳转到设备或模版注册的页面
            $scope.gotoRegister = function (type) {
                templateService.showAllTemplates(function (templates) {
                    var defaultMaintainTemplate = {
                        name: '默认模版（空）',
                        value: null
                    };
                    var options = [defaultMaintainTemplate];
                    ArrayUtils.ergodicArrayObject(this, templates, function (template) {
                        var templateSimple = {
                            name: template.templateName,
                            value: template.templateId,
                            after: {
                                ele: '<a href="javascript:;" class="fa-icon fa fa-remove red remove-template-' + template.templateId + '"></a>'
                            },
                            onclick: {
                                selector: '.remove-template-' + template.templateId,
                                func: function () {
                                    app.backEvent();
                                    $.confirm('确认删除模板[' + template.templateName + ']？', function () {
                                        templateService.removeByTemplateId(template.templateId, function () {
                                            $.alert('删除模板[' + template.templateName + ']成功');
                                        })
                                    })
                                }
                            }
                        };
                        options.push(templateSimple);
                    });
                    app.filterOptionsAction('选择模版', options, null, function (id) {
                        switch (type) {
                            default:
                            case 'device':
                                location.href = '#device-register' + (id != null && id != 'null' ? ('?templateId=' + id) : '');
                                break;
                            case 'template':
                                location.href = '#template-register' + (id != null && id != 'null' ? ('?templateId=' + id) : '');
                                break;
                        }
                    })
                });
            };

            // 根据设备编号删除设备
            $scope.deleteDevice = function (deviceNo) {
                $.confirm('确认删除设备[deviceNo = ' + deviceNo + ']？', function () {
                    deviceService.deleteDevice(deviceNo, function () {
                        $.alert('删除设备[deviceNo = ' + deviceNo + ']成功', function () {
                            history.back();
                        });
                        $scope.reloadDevices();
                    });
                });
            };

            $scope.loadDetailUrl = function (index) {
                location.href = '#detail?deviceIndex=' + index;
            };

            // 选择批量处理的动作
            $scope.chooseDeviceAction = function () {
                // 获取选中的设备
                var chooseDevices = [];
                ArrayUtils.ergodicArrayObject(this, $scope.chooseDevices, function (value, i) {
                    if (value) {
                        chooseDevices.push($scope.devices[i]);
                    }
                });
                if (chooseDevices.length < 1) {
                    $.toast('请至少选中一个设备', 1000, 'toastToBot');
                    return;
                }
                var chooseIds = ObjectUtils.parseTheSameObjectPropertyInArray(chooseDevices, 'deviceNo');
                app.filterOptionsAction('(待操作设备编号为:[' + chooseIds.deviceNo + '])选择并进行批量操作：', [
                    {
                        name: '添加运行时间',
                        value: 0
                    }
                ], 0, function (id) {
                    switch (id) {
                        default:
                        case 0: {
                            $.prompt('添加设备运行的时间（单位：h）',
                                function (value) {
                                    var recordChangedDuration = parseInt(value);
                                    if (!recordChangedDuration) {
                                        $.alert('请正确的输入一个数字！');
                                        return;
                                    }
                                    for (var i = 0; i < chooseDevices.length; i++) {
                                        chooseDevices[i].addRunningRecord(recordChangedDuration);
                                        deviceService.updateDevice(chooseDevices[i], function (message) {
                                            $.toast(message, 1000, 'toastToBot');
                                        });
                                    }
                                    $scope.reloadDevices();
                                    $scope.$digest();
                                    $.toast('批量操作执行完成', 1000, 'toastToBot');
                                }
                            );
                        }
                    }
                    $scope.isBatch = false;
                    $scope.$digest();
                })
            };

            $scope.test3 = function () {
                console.log($scope.chooseDevices);
            };

            // 测试
            $scope.test = function () {
                var a = {
                    a: {b: {c: {e: {a: 'asdsd'}}}, c: 'asd'},
                    b: 'asdf', f: new Date(),
                    c: [{a: 'ccc', b: ['asd', false, null]}, ['asd', 123456], [[[[[[{}, [{a: [[]]}]]]]]]]]
                };
                logger.debug(a);
                logger.time('测试开始-结束');
                var b = ObjectUtils.readLinkProperty(a, ['a.b.c.e.a', 'c.0.a', 'c.0.b.0', 'f.getTime()'], function (value, name) {
                    logger.debug(value, name);
                });
                logger.debug(b);
                logger.timeEnd('测试开始-结束');
            };
            $scope.test1 = function () {
                var a = {
                    a: {b: {c: {e: {a: 'asdsd'}}}, c: 'asd'},
                    b: 'asdf',
                    c: [{a: 'ccc', b: ['asd', false, null]}, ['asd', 123456], [[[[[[{}, [{a: [[]]}]]]]]]]]
                };
                logger.time('测试开始-结束');
                ObjectUtils.whileEmptyObjectProperty(this, a, 'a.b.c.e.a.e,a.b,a.c.0.b.1,,,a.c.0.b.2', function (name) {
                    logger.debug(name);
                });
                logger.timeEnd('测试开始-结束');
                ObjectUtils.whileEmptyObjectPropertyV2(this, a, 'a.b.c.e.a.e,a.b,a.c.0.b.1,,,a.c.0.b.2', function (name) {
                    logger.debug(name);
                });
            };
            $scope.test_go = function () {
                logger.debug($route);
                $route.updateParams({
                    dd: $scope.devices
                });
                $route.logger.debug($routeParams)
            };
            $scope.test_can_get_statistics = function () {
                logger.time('获取所有设备的统计信息');
                var statistics = Device.generateStatistics($scope.devices);
                logger.timeEnd('获取所有设备的统计信息');
                logger.debug(statistics);
            };

            /**
             * 更新app
             * @param path 网络路径
             */
            $scope.updateApp = function (path) {
                if (!window.plus) {
                    $.alert('请在手机上使用该功能');
                }
                var wait = plus.nativeUI.showWaiting('更新中');
                var dtask = plus.downloader.createDownload(path, {}, function (d, status) {
                    wait.close();
                    if (status == 200) {
                        plus.runtime.install(d.filename, {}, function () {
                            plus.runtime.restart();
                        }, function (e) {
                            $.alert(e.message);
                        });
                    } else {
                        $.alert("下载更新文件失败: " + status);
                    }
                });
                dtask.addEventListener("statechanged", function () {
                    wait.setTitle('更新中(' + (dtask.downloadedSize / 1024).toFixed(2) + 'kb/' + (dtask.totalSize / 1024).toFixed(2) + 'kb)');
                }, false);
                dtask.start();
            };

            /**
             * 检查app版本是否需要更新
             */
            $scope.checkVersion = function (isShowInfo) {
                app.onPlusReady(function () {
                    var version = plus.runtime.version;
                    $http({
                        url: 'http://palerock.cn/file/device-version-info.jsp',
                        method: 'get'
                    }).then(
                        function (res) {
                            var info = res.data;
                            if (!info.error) {
                                var nowVersion = info.version;
                                if (nowVersion && info.path && $.compareVersion(nowVersion, version) == 1) {
                                    $.confirm('发现新版本，马上更新？[更新内容:' + info.content + ']', function () {
                                        $scope.updateApp(info.path);
                                    });
                                } else {
                                    if (isShowInfo) {
                                        $.alert('已是最新版本无需更新');
                                    }
                                }
                            } else {
                                if (isShowInfo) {
                                    $.alert('已是最新版本无需更新');
                                }
                            }
                        }, function (res) {
                            if (res.status == -1) {
                                if (isShowInfo) {
                                    $.alert('请在检查网络连接是否能够正常工作后重试！');
                                }
                            } else {
                                if (isShowInfo) {
                                    $.alert('服务器开了个小差~访问失败！');
                                }
                            }
                        }
                    )
                });
            };

            $scope.checkVersion();

            $scope.exit = function () {
                if (window.plus) {
                    $.confirm('退出程序？', function () {
                        plus.runtime.quit();
                    });
                }
            };
            // 更多...
        }
    );
});